<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Console\Commands;

use App\Models\CensusUserNativePlace as CensusUserNativePlaceModel;
use App\Models\UserProfile;
use Illuminate\Console\Command;

class CensusUserNativePlace extends Command
{
    const PROVINCES = [
        '北京市' => '北京',
        '天津市' => '天津',
        '河北省' => '河北',
        '山西省' => '山西',
        '内蒙古自治区' => '内蒙',
        '辽宁省' => '辽宁',
        '吉林省' => '吉林',
        '黑龙江省' => '黑龙江',
        '上海市' => '上海',
        '江苏省' => '江苏',
        '浙江省' => '浙江',
        '安徽省' => '安徽',
        '福建省' => '福建',
        '江西省' => '江西',
        '山东省' => '山东',
        '河南省' => '河南',
        '湖北省' => '湖北',
        '湖南省' => '湖南',
        '广东省' => '广东',
        '广西壮族自治区' => '广西',
        '海南省' => '海南',
        '重庆市' => '重庆',
        '四川省' => '四川',
        '贵州省' => '贵州',
        '云南省' => '云南',
        '西藏自治区' => '西藏',
        '陕西省' => '陕西',
        '甘肃省' => '甘肃',
        '青海省' => '青海',
        '宁夏回族自治区' => '宁夏',
        '新疆维吾尔自治区' => '新疆',
        '香港特别行政区' => '香港',
        '澳门特别行政区' => '澳门',
        '台湾省' => '台湾',
    ];

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'census:user_native_place';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '统计用户籍贯';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 统计北京的用户数量
        foreach (self::PROVINCES as $province => $provinceLike) {
            $this->census($province, $provinceLike);
        }
        return 0;
    }

    private function census(string $province, string $provinceLike)
    {
        $userNumber = UserProfile::query()->where('native_place', 'like', $provinceLike . '%')->count();
        if (CensusUserNativePlaceModel::query()->where('province', $province)->exists()) {
            CensusUserNativePlaceModel::query()->where('province', $province)->update([
                'user_num' => $userNumber,
                'census_time' => time(),
                'province' => $province,
            ]);
        } else {
            CensusUserNativePlaceModel::query()->where('province', $province)->create([
                'user_num' => $userNumber,
                'census_time' => time(),
                'province' => $province,
            ]);
        }
    }
}
